package com.mediastory.spsserver.notice.service.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.mediastory.spsserver.notice.dao.NoticeDao;
import com.mediastory.spsserver.notice.domain.Notice;
import com.mediastory.spsserver.notice.service.NoticeSvc;
import com.Ostermiller.util.Base64;

/**
 * Notice SvcImpl
 * @author Jaewon Choi
 *
 */

@Service
@Transactional
public class NoticeSvcImpl implements NoticeSvc {

	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	NoticeDao noticeDao;
	
	public NoticeSvcImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Notice> findbyList(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Notice>) (noticeDao.SelectList(condition));
	}

	public Map<String, Object> findbyListPaging(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("noticeList", (List<Notice>) (noticeDao.SelectList(condition)));
		resultMap.put("noticeListTotalCnt", (Integer) (noticeDao.SelectListTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public Notice findby(Integer idx) throws Exception {
		// TODO Auto-generated method stub
		return noticeDao.select(idx);
	}
	
	public Notice findby(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		
		return noticeDao.select(condition);
	}

	@Override
	public Notice add(Notice notice) throws Exception {
		// TODO Auto-generated method stub
		
		Notice result = null;
		File file = null;
		try {
			//파일 업로드
			MultipartFile imgFile = notice.getImgFile();
			if(imgFile != null && ! imgFile.isEmpty() && imgFile.getContentType().contains("image")){
				long time = Calendar.getInstance().getTimeInMillis();
				String prefixNm = Base64.encode((URLEncoder.encode(notice.getTitle(),"utf-8")+Long.toString(time)));
				//업로드 경로
				String uploadDir = messages.getMessage("file.notice.uploadDir");
				//viewUrl
				String viewUrl = messages.getMessage("file.notice.viewUrl");
				
				String fileNm = prefixNm + "."+(imgFile.getOriginalFilename()).split("\\.")[1];

				file = new File(uploadDir+fileNm);
				String url = viewUrl+fileNm;
				notice.setImgUrl(url);
				
				if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
					new File(uploadDir).mkdirs();
				}
				imgFile.transferTo(file);
			}
			
			result = noticeDao.insert(notice);	
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			if(file != null){
				file.delete();
			}
			
			throw e;
		}
		
		return result;
	}

	@Override
	public Notice modify(Notice notice) throws Exception {
		// TODO Auto-generated method stub
		
		File file = null;
		try {
			//파일 업로드
			MultipartFile imgFile = notice.getImgFile();
			if(imgFile != null && ! imgFile.isEmpty() && imgFile.getContentType().contains("image")){
				long time = Calendar.getInstance().getTimeInMillis();
				String prefixNm = Base64.encode((URLEncoder.encode(notice.getTitle(),"utf-8")+Long.toString(time)));
				//업로드 경로
				String uploadDir = messages.getMessage("file.notice.uploadDir");
				//viewUrl
				String viewUrl = messages.getMessage("file.notice.viewUrl");
				
				String fileNm = prefixNm + "."+(imgFile.getOriginalFilename()).split("\\.")[1];

				file = new File(uploadDir+fileNm);
				String url = viewUrl+fileNm;
				notice.setImgUrl(url);
				
				if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
					new File(uploadDir).mkdirs();
				}
				imgFile.transferTo(file);
			}
			
			notice = noticeDao.update(notice);
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			if(file != null){
				file.delete();
			}
			
			throw e;
		}

		return notice;
	}

	@Override
	public int remove(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return noticeDao.delete(condition);
	}
	
	public int modifyIsMain(Integer idx) throws Exception {
		
		int result = 0;
		Map<String, Object> condition = new HashMap<String, Object>();
		
		//전부 isMain = 0
		condition.put("isMain", 0);
		result = noticeDao.updateSetIsMain(condition);
		
		//isMain 설정
		if(idx != null){
			condition.put("isMain", 1);
			condition.put("idx", idx);
			result = noticeDao.updateSetIsMain(condition);	
		}

		return result;
	}

}